<template>
  <div class="box">
    <header class="header">
      <div class="van-nav-bar_title">购物车</div>
    </header>
    <div class="content">
      <div class="noshop" v-if="shopFlag">
        <div class="title">
         <van-checkbox v-model="allchecked" @click="selectAll" class="check"></van-checkbox>
          <div class="flyco">飞科商城</div>
        </div>
        <div class="is_empty">
          <img src="https://img11.360buyimg.com/jdphoto/s180x180_jfs/t18163/292/540553659/74408/adeb7463/5a93c51cN3bb5e37b.png" alt="无商品" width="20%">
          <div>您的购物车空空如也~</div>
        </div>
        <van-submit-bar
          :price="totalPrice * 100"
          :button-text="'结算(' + totalNum + ')'"
          @submit="onSubmit"
        >
          <van-checkbox v-model="allchecked" @click="selectAll">全选</van-checkbox>
        </van-submit-bar>
      </div>
      <div class="shopping" v-else>
        <van-notice-bar text="列表向左滑动可以删除该商品" left-icon="volume-o" mode="closeable"/>
        <van-swipe-cell  v-for="(item, index) of cartlist" :key="item.cartid">
          <van-card
            :num="item.num"
            :price="item.price"
            :title="item.name"
          >
            <div slot="thumb">
              <!-- <van-checkbox v-model="item.flag" @change="selectItem(item)"></van-checkbox> -->
              <input type="checkbox" v-model="item.flag" @change="selectItem(item, $event)">
              <img :src="item.proimg" style="width: 0.8rem;" alt="">
            </div>
            <div slot="tags">
              <van-tag plain type="danger">{{ item.brand }}</van-tag>
            </div>
            <div slot="footer">
              <van-button size="mini" @click="add(item)">+</van-button>
              <van-button :disabled="item.num <= 1" size="mini" @click="reduce(item)">-</van-button>
            </div>
          </van-card>
          <template #right>
            <van-button
              square
              text="删除"
              type="danger"
              class="delete-button"
              @click="deleteItem(item.cartid, index)"
            />
          </template>
        </van-swipe-cell>
        <van-submit-bar
          :price="totalPrice * 100"
          :button-text="'结算(' + totalNum + ')'"
          @submit="onSubmit"
        >
          <van-checkbox v-model="allchecked" @click="selectAll">全选</van-checkbox>
        </van-submit-bar>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { getCartData, updateCartData, deleteCartData, addOrder } from '@/api'
import { NavBar, Card, Tag, Button, SwipeCell, NoticeBar, Dialog, SubmitBar, Checkbox, Toast } from 'vant'
Vue.use(NavBar)
Vue.use(Card)
Vue.use(Tag)
Vue.use(Button)
Vue.use(SwipeCell)
Vue.use(NoticeBar)
Vue.use(Dialog)
Vue.use(SubmitBar)
Vue.use(Checkbox)
Vue.use(Toast)
export default {
  data () {
    return {
      cartlist: [],
      allchecked: true
    }
  },
  computed: {
    shopFlag () {
      return this.cartlist.length === 0
    },
    totalPrice () {
      return this.cartlist.reduce((sum, item) => {
        return item.flag ? sum + item.price * item.num : sum + 0
      }, 0)
    },
    totalNum () {
      return this.cartlist.reduce((sum, item) => {
        return item.flag ? sum + item.num : sum + 0
      }, 0)
    }
  },
  mounted () {
    getCartData({
      userid: localStorage.getItem('userid')
    }).then(res => {
      this.cartlist = res.data.data
    })
  },
  methods: {
    add (item) {
      updateCartData({ cartid: item.cartid, num: item.num + 1 }).then(res => { // 数据库更新完毕
        console.log(res.data)
        if (res.data.code === '200') {
          item.num += 1 // 修改页面
        }
      })
    },
    reduce (item) {
      // item.num -= 1
      updateCartData({
        cartid: item.cartid,
        num: item.num > 1 ? item.num - 1 : 1
      }).then(res => { // 数据库更新完毕
        console.log(res.data)
        if (res.data.code === '200') {
          item.num > 1 ? item.num -= 1 : item.num = 1
        }
      })
    },
    deleteItem (cartid, index) {
      Dialog.confirm({
        title: '删除',
        message: '你确认要删除该商品吗？'
      }).then(() => {
        // on confirm
        deleteCartData({ cartid }).then(res => {
          if (res.data.code === '200') {
            // 修改状态
            this.cartlist.splice(index, 1)
          }
        })
      }).catch(() => {
        // on cancel
      })
    },
    selectItem (item, event) {
      console.log(item)
      console.log(event.target.checked)
      // 后端实现接口，给后端传入 cartid 以及 event.target.checked，如果成功执行以下操作
      item.flag = event.target.checked
      if (event.target.checked) {
        this.allchecked = this.cartlist.every(item => {
          return item.flag
        })
      } else {
        this.allchecked = false
      }
    },
    selectAll (event) {
      this.allchecked = !this.allchecked
      this.cartlist.map(item => {
        item.flag = this.allchecked
      })
    },
    onSubmit () {
      // 判定有没有选中商品，没有给予提示
      if (this.totalNum === 0) {
        Toast.fail('请先勾选你要购买的东西')
      } else {
        // Toast('确认订单')
        const arr = []
        this.cartlist.map(item => {
          if (item.flag) {
            arr.push(item)
          }
        })
        addOrder({
          userid: localStorage.getItem('userid'),
          orderlist: JSON.stringify(arr)
        }).then(res => {
          console.log(res)
          // 返回一个订单id，跳转页面传递订单id
          this.$router.push('/order/' + res.data.orderid)
        })
      }
    }
  }
}
</script>

<style lang="scss">
.header {
  height: .63rem;
  line-height: .63rem;
  font-size: .24rem;
  // position: fixed;
  .van-nav-bar {
    width: 100%;
    text-align: center;
    border-bottom: 1px solid #e5e5e5;
  }
  .van-nav-bar_title {
    max-width:100%;
    margin: 0 auto;
    color: #323233;
    font-weight: 500;
    background-color: #fff;
  }
  .editor_head {
    font-size: .15rem;
    position: absolute;
    right:1.8rem;
    top:0.03rem;
    color: #323233;
  }
}
.content {
  .check {
    float: left;
    // margin:0.1rem;
    padding-left: .1rem;
    padding-right: .2rem;
    // margin-top: .63rem;
  }
  .flyco {
    margin-top: .1rem;
    margin-left: .1rem;
    font-size: .16rem;
  }
  .is_empty {
    padding-top: .6rem;
    text-align: center;
    img {
      width: .8rem;
    }
  }
}
.van-submit-bar {
  border-top: 1px solid #e5e5e5;
  border-bottom: 1px solid #e5e5e5;
  bottom: .6rem;
}
.van-submit-bar__button {
  width:  .9rem;
  height: .4rem;
}
.van-button--round {
  border-radius: 0px;
}
</style>
